// pages/persondz/persondz.js
const app = getApp();

var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
var times = 3,
  sw = wx.getSystemInfoSync().windowWidth;
var system = wx.getSystemInfoSync().platform;
Page({
  data: {
    zindex: 2,
    isLogin: false,
    pid: '',
    xgimg: '',
    headurl: '',
    color: 'fff',
    imgid: '',
    image: 'https://pertailor.oss-cn-shenzhen.aliyuncs.com/2019-09-29/49e49b2f544b4e6d9e7a01f7b373686a.png',
    checked: false,
    animation: '',
    imgAnimation: '',
    location: '',
    talk: '',
    name: '',
    zheng: true,
    textFront: '28rpx',
    canvasW: '',
    canvasH: '',
    type: '',
    fromwho: '',
    le: '',
    flage: false,
  },
  onLoad: function(options) {
    qqmapsdk = new QQMapWX({
      key: 'HKWBZ-AX76O-QIUWP-SFHFY-B36TF-SLF24' //这里自己的key秘钥进行填充
    });
    this.setData({
      canvasW: sw * times,
      canvasH: (1080 / 1919) * sw * times,
      /*1080/1919背景图比例 */
    })
    if (options.type == 'orderedit') { //订单或购物车跳转修改
      this.setData({
        checked: true,
        location: options.location,
        color: options.color,
        name: options.name,
        talk: options.talk,
        image: options.image,
        // pid: options.imgid,
        type: options.type,
        sonid: options.sonid,
        fromwho: options.fromwho,
        pid: options.pid,
      })
    } else {
      this.getimgs();
    }
    console.log(wx.getSystemInfoSync().platform)

  },
  onReady: function() {
    this.animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear',
      transformOrigin: '50% 50% 0',
      success: function(res) {}
    })
  },

  onShow: function() {
    let pages = getCurrentPages();
    this.setData({
      image: this.data.image,
      imgid: this.data.imgid,
      color: this.data.color,
      pid: this.data.pid,
      bgtalk: this.data.talk,
    })

  },
  getimgs() { //获取系统背景图
    if (wx.getStorageSync('bgimgs')){
      let bgimgs = JSON.parse(wx.getStorageSync('bgimgs'));
      console.log(bgimgs)
      this.setData({
        image: bgimgs[0].url,
        pid: bgimgs[0].pid
      });
    }else{
    wx.showLoading({
      title: '加载中...'
    })
    let _that = this;
    wx.request({ //传后台
      url: app.globalData.url + '/jxb/goods/goods/getBackground',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {},
      success: function(res) {
        if (res.data.code == 0) {
          _that.setData({
            image: res.data.data[0].url,
            pid: res.data.data[0].pid
          });
        } else {
          wx.showToast({
            title: '网络错误',
            duration: 2000,
            icon: 'none'
          });
        }
      },
      fail: function(err) {
        wx.showToast({
          title: '网络错误',
          duration: 2000,
          icon: 'none'
        });
      },
      complete: function() {
        wx.hideLoading()
      },
    })
    }
  },
  bindtap1: function(e) { //协议选中

    let that = this;
    that.setData({
      checked: !that.data.checked
    })
  },
  detail: function(e) { //查看说明协议
    wx.navigateTo({
      url: '/pages/persondz/detailexplain/detailexpalin?type=persondz'　　 // 协议页面
    })
  },

  uporder: function() { //提交订单
    if (wx.getStorageSync('token')) {
      if (this.data.checked == true) {
        let that = this;
        if (this.data.location == '' || this.data.location == '·' || this.data.name == '' || this.data.talk == '' || this.data.talk.match(/^\s+$/) || this.data.name.match(/^\s+$/)) {
          let content = '';
          this.data.location == '' ? content = '亲，请选择位置' : this.data.location == '·' ? content = '亲，请选择位置' : this.data.name == '' ? content = '亲，请落款' : this.data.talk == '' ? content = '亲，请先填写或选择想说的话喔' : this.data.talk.match(/^\s+$/) ? content = '亲，请先填写或选择想说的话喔' : this.data.name.match(/^\s+$/) ? content = '亲，请填写落款喔' :'请完善信息'
          wx.showModal({
            title: '稍等一下',
            confirmText: '好的',
            confirmColor: '#28A8F9',
            showCancel: false,
            content: content,
            success: function(res) {
              if (res.confirm) {} else if (res.cancel) {
                return;
              }
            }
          })
        } else if (that.data.location !== '' && that.data.name !== '' && that.data.talk !== '') {
          that.checkuser()
          // if (that.checkuser()){
          //   that.canvascontent();
          // }
         
        }
      } else {
        wx.showToast({
          title: '请同意并阅读《江小白私人定制特别说明》',
          duration: 2000,
          icon: 'none'
        })
      }
    }
  },
  rotate: function() { //动画旋转 
    this.animation.rotateY(90).step();
    this.setData({
      //输出动画
      animation: this.animation.export()
    })
    setTimeout(() => {
      this.animation.rotateY(0).step()
      this.setData({
        animation: this.animation.export(),
        zheng: !this.data.zheng,
      })
      if (this.data.zheng == true) {
        this.setData({
          zindex: 2,
        })
      } else {
        this.setData({
          zindex: -1,
        })
      }
    }, 400)

  },

  getlation: function() { //选择位置
    console.log(1)
    let that = this;
    wx.chooseLocation({
      success(res) {
        console.log(res)
        var latitude = res.latitude
        var longitude = res.longitude
        that.getLocal(latitude, longitude)
      }
    });

  },
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(res);
        let city = res.result.ad_info.city
        let district = res.result.ad_info.district    
        let locationstr = city + '·' + district;
        console.log(locationstr)
        vm.setData({
          location: locationstr,
          border: 'none',
          background: 'rgba(255, 255, 255, .1)'
        });
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },

  openMap: function(e) {
    wx.authorize({
      scope: 'scope.userLocation',
      success: (res) => {

      },
    });
    var that = this
    wx.getSetting({
      success(res) {
        //这里判断是否有地位权限
        if (!res.authSetting['scope.userLocation']) {

          wx.showModal({
            title: '提示',
            content: '请求获取位置权限',
            success: function(res) {
              if (res.confirm == false) {

                return false;
              }
              wx.openSetting({
                success(res) {
                  //如果再次拒绝则返回页面并提示
                  if (!res.authSetting['scope.userLocation']) {
                    wx.showToast({
                      title: '请授权',
                      duration: 2000,
                      icon: 'none'
                    })
                  } else {
                    //允许授权，调用地图

                    that.getlation()
                  }
                }
              })
            }
          })
        } else {

          //如果有定位权限，调用地图
          that.getlation()
        }

      }

    })
  },
  find(str) {

  },
  getstr() {
    // this.setData({
    //   bgtalk: this.data.talk.replace(/[\r\n]/g, "")
    // })
    // if (this.data.flage == true) {
    //   let le = this.data.le;
    //   console.log(le)
    //   this.setData({
    //     talk: this.data.talk.substr(0, le)
    //   })
    //   wx.showToast({
    //     title: '最多输入36个字符或5行',
    //     duration: 2000,
    //     icon: 'none'
    //   })
    // }
  },
  talkinp(e) { //获取说的话
    // const query = wx.createSelectorQuery()
    // query.select('.talk').boundingClientRect()
    // query.selectViewport().scrollOffset()
    // let that = this
    // query.exec(function(res) {
    //   res[0].top // #the-id节点的上边界坐标
    //   res[1].scrollTop // 显示区域的竖直滚动位置
    //   // console.log('打印demo的元素的信息', res);
    //   console.log('打印高度', res[0].height);
    //   if (res[0].height == 136) {
    //     console.log(res[0])
    //     that.setData({
    //       le: res[0].dataset.itrm.length,
    //       flage: true,
    //       talk: e.detail.value,
    //     })
    //   } else if (res[0].height < 136) {
    //     that.setData({
    //       flage: false,
    //     })
    //   }
    // })

    let n = (e.detail.value.split('\n')).length - 1
    if (parseInt(e.detail.value.length) >= 30 ||n>=5) {
      // this.setData({
      //   maxlength: parseInt(e.detail.value.length)
      // })
      wx.showToast({
        title: '最多输入30个字符或5行',
        duration: 2000,
        icon: 'none'
      })
    }
      console.log(e.detail.value)
      this.setData({
        talk: e.detail.value,
        bgtalk: e.detail.value,
        // maxlength: '',
      })

  },
  nameinp(e) { //获取姓名
    if (parseInt(e.detail.value.length) >= 5) {
      wx.showToast({
        title: '最多输入5个字符',
        duration: 2000,
        icon: 'none'
      })
    }
    this.setData({
      name: e.detail.value,
    })
  },
  inputFocus() { //落款获取焦点
    this.setData({
      border1: '1px solid #fff',
    })
  },
  inputBlur() { //落款失去焦点
    this.setData({
      border1: 'none',
      background1: 'rgba(255, 255, 255, .1)'
    })
  },
  upimg() { //上传图片
    if (this.data.checked == false) {
      wx.showToast({
        title: '请同意并阅读《江小白私人定制特别说明》',
        duration: 2000,
        icon: 'none'
      })

    } else if (wx.getStorageSync('token')) {
      wx.navigateTo({
        url: '/pages/upimg/upimg?talk=' + this.data.talk + '&name=' + this.data.name + '&location=' + this.data.location + '&color=' + this.data.color + '&imgurl=' + this.data.image,
      })
    }
  },
  saveedit(pidiurl) { //提交订单修改
    if (this.data.checked == false) {
      wx.showToast({
        title: '请同意并阅读《江小白私人定制特别说明》',
        duration: 2000,
        icon: 'none'
      })
    } else {
      if (this.data.location !== '' && this.data.name !== '' && this.data.talk !== '') {
        wx.showLoading({
          title: '加载中...',
          mask: true,
        })
        let url1 = '';
        let urlto = '';
        if (this.data.fromwho == 'order') {
          url1 = app.globalData.url + '/jxb/order/updateOrder';
          // urlto = '/pages/myorder/myorder'
        } else if (this.data.fromwho == 'car') {
          url1 = app.globalData.url + '/jxb/goods/updateCart';
          // urlto = '/pages/shopcar/shopcar';
        }
        let _that = this;
        wx.request({ //传后台
          url: url1,
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            pid: _that.data.pid,
            pidiurl: pidiurl,
            loan: _that.data.name,
            quotation: _that.data.talk,
            position: _that.data.location,
            token: wx.getStorageSync('token'),
            tcolor: _that.data.color == 0 ? 0 : 1,
            sonid: _that.data.sonid,
            url: _that.data.image,
          },
          success: function(res) {
            wx.showToast({
              title: '修改成功',
              duration: 2000,
              icon: 'success'
            })
            if (_that.data.fromwho == 'order') {
              wx.navigateTo({
                url: '/pages/myorder/myorder'
              })
            } else if (_that.data.fromwho == 'car') {
              wx.switchTab({
                url: '/pages/shopcar/shopcar'
              })
            }

            // wx.navigateBack({ delta: 2})                     
          },
          fail: function(res) {
            wx.showToast({
              title: '网络错误',
              duration: 2000,
              icon: 'none'
            })
          },
          complete: function() {
            wx.hideLoading()
          },
        })
      } else {
        wx.showModal({
          title: '稍等一下',
          confirmText: '好的',
          confirmColor: '#28A8F9',
          showCancel: false,
          content: '亲，请完善填写信息',
          success: function(res) {
            if (res.confirm) {} else if (res.cancel) {
              return;
            }
          }
        })
      }
    }
  },
  orderedit() { //修改提交
    this.canvascontent();
  },
  login: function() { //登录
    wx.showLoading({ title: '登录中...', });
    let that = this;
    wx.login({
      success: res => {
        if (res.code) { //有code
          app.globalData.code = res.code;
          wx.getSetting({
            success: function(res) { //已授权
              if (res.authSetting['scope.userInfo']) {
                wx.getUserInfo({ //调用用户信息
                  success: res => { //获取信息   
                    wx.setStorageSync('headurl', res.userInfo.avatarUrl);
                    wx.setStorageSync('username', res.userInfo.nickName);
                    wx.request({ //传后台
                      url: app.globalData.url + '/jxb/login/login/loginAuth',
                      method: 'POST',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      data: {
                        code: app.globalData.code,
                        encryptedData: res.encryptedData,
                        iv: res.iv
                      },
                      success: function(res3) {
                        if(res3.data.code==0){
                          wx.hideLoading();
                          wx.setStorageSync('token', res3.data.data.token);
                          wx.setStorageSync('uid', res3.data.data.uid);
                          app.globalData.isLogin = true;
                          that.data.isLogin = true;
                          console.log(wx.getStorageSync('tel'))
                          if (!(wx.getStorageSync('tel'))) {
                            that.setData({
                              telshow: 'block',
                              telzindex: 8,
                            })
                          } else {
                            that.setData({
                              telshow: 'none',
                              telzindex: 0,
                            })
                          }
                          wx.showToast({
                            title: res3.data.msg,
                            duration: 2000,
                            icon: 'none',
                          })  
                        }else{
                          wx.showToast({
                            title: res3.data.msg,
                            duration: 2000,
                            icon: 'none',
                          })
                        }
                        
                      },

                    })
                  }
                })
              } else { //未授权
                that.getUserInfo();
              }
            }

          }); // 查看授权

        } else { //没有code

        }
      }
    })
  },
  getUserInfo(res) { //授权
    if (res.detail.userInfo) {
      console.log("点击了同意授权");
      if (!wx.getStorageSync('token')) {
        this.login();
      }
    } else {
      console.log("点击了拒绝授权");
    }

  },
  getPhoneNumber(e) { //获取电话号码
    var data = {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      token: wx.getStorageSync('token'),
    }
    let that = this;
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      wx.request({
        method: "post",
        url: app.globalData.url + '/jxb/login/login/getPhoneNumber',
        data: data,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          wx.setStorageSync('tel', res.data.data.tel);
          that.saveinfo('', res.data.data.tel,'')
          console.log(wx.getStorageSync('tel'))
          that.setData({
            telzindex: 0,
            telshow: 'none'
          });
          wx.hideLoading()
          wx.showToast({
            title: '授权成功',
            icon: 'success',
            duration: 2000
          })
        },
        fail: function(res) {
          console.log(res)
        }
      })

    }

  },
  saveinfo(remark, tel, avatar) { //保存信息
    wx.request({
      url: app.globalData.url + '/jxb/oneself/updateUserInfo',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        token: wx.getStorageSync('token'),
        uid: wx.getStorageSync('uid'),
        remark: remark,
        tel: tel,
        avatar: avatar,
      },
      success: function (res) {
        // wx.showToast({
        //   title: '修改成功',
        //   icon: 'success',
        //   duration: 2000
        // })
      },

    })
  },
  canvascontent: function() { //生成图片
    wx.showLoading({
      title: '正在生成图片...',
      mask: true,
    })
    var height = 0;
    var color = '';
    this.data.color == 'fff' ? color = "#fff" : color = '#29A6F8';
    var that = this;
    const ctx = wx.createCanvasContext('demo');
    ctx.font = 'normal normal 12px 微软雅黑';
    ctx.setFontSize(toPx(18));
    ctx.setTextBaseline('top');
    ctx.setTextAlign('left');
    //  画背景图（网络图片需要先下载）  
    let p1 = new Promise((resolve, reject) => {
      wx.downloadFile({
        url: 'https://pertailor.oss-cn-shenzhen.aliyuncs.com/2019-09-02/c67e6b4dcefd4ada9e7bdf549b620f6c.png',
        success: res => {
          if (res.statusCode == 200) {
            var img = res.tempFilePath;
            resolve(img)
            ctx.drawImage(img, 0, 0, this.data.canvasW, this.data.canvasH)
          }
        }

      });
    });
    let p2 = new Promise((resolve, reject) => {
      let that = this;
      wx.downloadFile({
        url: that.data.image,
        success: res => {
          if (res.statusCode == 200) {
            var img = res.tempFilePath;
            resolve(img)
            ctx.drawImage(img, toPx(545), toPx(206), toPx(192), toPx(204))
            ctx.drawImage(img, toPx(324), toPx(336), toPx(49), toPx(49))
          }
        }

      });
    });
    //画图
    Promise.all([p1, p2]).then((result) => {

      var param = {
        str: that.data.talk,
        ctx: ctx,
        ellipsis: true,
        len: 178
      }
      var param1 = {
        str: (that.data.talk).replace(/[\r\n]/g, "").replace(/\ +/g, ""),
        ctx: ctx,
        ellipsis: true,
        len: 178
      }
      var len1 = fillLinesText(param1).length;
      var len = fillLinesText(param).length;
      ctx.setTextAlign('left');
      for (var i = 0; i < len1; i++) { //背面的字
        ctx.setFillStyle('#29A6F8');
        ctx.fillText(fillLinesText(param1)[i], toPx(328), toPx(216 + 24 * i));
        console.log(toPx(328))
      }
      ctx.setTextAlign('left');
      for (var j = 0; j < len; j++) { //正面的字
        ctx.setFillStyle(color);
        ctx.fillText(fillLinesText(param)[j], toPx(556), toPx(216 + 24 * j));
        console.log(toPx(556))
      }

    //   if (system =='android'){     
    //   for (var i = 0; i < len1; i++) { //背面的字
    //     ctx.setFillStyle('#29A6F8');
    //     ctx.fillText(fillLinesText(param1)[i], toPx(390), toPx(216 + 24 * i));
    //     console.log(toPx(328))
    //   }
    //   for (var j = 0; j < len; j++) { //正面的字
    //     ctx.setFillStyle(color);
    //     ctx.fillText(fillLinesText(param)[j], toPx(618), toPx(216 + 24 * j));
    //     console.log(toPx(556))
    //   }
    // }else{
    //     for (var i = 0; i < len1; i++) { //背面的字
    //       ctx.setFillStyle('#29A6F8');
    //       ctx.fillText(fillLinesText(param1)[i], toPx(328), toPx(216 + 24 * i));
    //       console.log(toPx(328))
    //     }
    //     for (var j = 0; j < len; j++) { //正面的字
    //       ctx.setFillStyle(color);
    //       ctx.fillText(fillLinesText(param)[j], toPx(556), toPx(216 + 24 * j));
    //       console.log(toPx(556))
    //     }
    //   }
      // 落款
      ctx.setFontSize(toPx(10));
      ctx.setTextAlign('right');
      ctx.setFillStyle(color);
      ctx.fillText('【' + that.data.name + '】', toPx(724), toPx(360));
      ctx.setFillStyle('#29A6F8');
      ctx.fillText('【' + that.data.name + '】', toPx(490), toPx(290));
      // 定位
      ctx.setTextAlign('right');
      ctx.setFillStyle(color);
      ctx.fillText(that.data.location, toPx(724), toPx(380));
      ctx.setFillStyle('#29A6F8');
      ctx.fillText(that.data.location, toPx(490), toPx(310));
      ctx.draw(true, () => {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          destWidth: that.data.canvasW, //画布宽高*dpr 以iphone6为准
          destHeight: that.data.canvasH,
          canvasId: 'demo',
          success: function(res) {
           that.changehead(res.tempFilePath); //上传效果图
          
            // wx.previewImage({
            //   urls: [res.tempFilePath],
            // })

          }
        })
      });
    }).catch((error) => {
      console.log(error) // 失败了，打出 '失败'
    })

  },
  changehead(path) { //上传效果图
    console.log(this.data.pid)
    let that = this;
    wx.uploadFile({
      url: app.globalData.url + '/jxb/login/login/uploadAvatar', //仅为示例，非真实的接口地址
      filePath: path,
      name: 'files',
      formData: {
        'user': 'test'
      },
      success(res) {
        let data = JSON.parse(res.data)
        that.setData({
          xgimg: data.data.url,
        })
        if (that.data.type == 'orderedit') {
          that.saveedit(data.data.url)
        } else {
          wx.hideLoading();
          wx.navigateTo({
            url: '/pages/sureorder/sureorder?talk=' + that.data.talk + '&name=' + that.data.name + '&location=' + that.data.location + '&imgid=' + that.data.imgid + '&imgurl=' + that.data.image + '&color=' + that.data.color + '&xgimg=' + that.data.xgimg + '&pid=' + that.data.pid,
            　　 // 确认订单详情
          })
        }

      }
    })
  },
  checkuser(){
    let that = this;
    wx.request({ //获取购物车列表
      url: app.globalData.url + '/jxb/goods/goods/verifyStatus',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        token: wx.getStorageSync('token'),
      },
      success: function (res) {
        
        if(res.data.code==405){
          wx.showModal({
            title: '提示',
            content: '帐号异常，已被封禁，请联系客服处理',
            showCancel: false,
            cancelText: '',
            cancelColor: '',
            confirmText: '确定',
            confirmColor: '#2AA7F9',
            success: function (res) {
              if (res.confirm) {
                wx.switchTab({
                  url: '/pages/index/index',
                })
              }
            },
           
          })
          return false
        }else{
          that.canvascontent();
          return true;
        }
      }
   })
  }

})

function fillLinesText(param) {
  var str = "",
    brr = [],
    arr = param.str.split("");
  if (!param.line) param.line = 999

  for (var j = 0; j < param.line; j++) {

    var wrap = false;
    if (arr.length) {
      for (var i = 0; i < arr.length; i++) {
        str += arr[i];
        if (arr[i].match(/[\r\n]/g)) {
          wrap = true;
          brr.push(str.substring(0, str.length - 1))
          arr = arr.slice(str.length - 1);
          arr.splice(0, 1);
          str = "";
          break;
        }
        const metrics = param.ctx.measureText(str);
        if (metrics.width > toPx(param.len)) {
          wrap = true;
          if (j == param.line - 1 && param.ellipsis) {
            brr.push(str.substring(0, str.length - 2) + '…')
          } else {
            brr.push(str.substring(0, str.length - 1));
          }
          arr = arr.slice(str.length - 1);
          str = "";
          break;
        }
      }
      if (wrap == false) {
        brr.push(str);
        arr = [];
      }
    }

  }
  return brr
}
var toPx = (l) => {
 
  return Math.ceil(l / (750 / sw)) * times;
}